import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/store/user'
import cart from '@/store/cart'

Vue.use(Vuex)

const LoginPlugin = store => {
    store.subscribe((mutation, state) => {
        if (mutation.type.includes('user')) {
            // console.log({ mutation, state })
            localStorage.setItem('user', JSON.stringify(state.user.user))
        }
    })
}

const CartPlugin = store => {
    store.subscribe((mutation, state) => {
        if (mutation.type.includes('cart')) {
            // console.log(store)
            localStorage.setItem('cart', JSON.stringify(state.cart.cartItemList))
            // 待整理
            let cartData = localStorage.getItem('cartData') ? JSON.parse(localStorage.getItem('cartData')) : []
            const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : { username: '游客' }
            if (cartData.some(item => item.username === user.username)) {
                cartData = cartData.map(item => {
                    if (item.username === user.username) {
                        item.cartList = state.cart.cartItemList
                    }
                    return item
                })
            } else {
                cartData.push({
                    username: user.username,
                    cartList: state.cart.cartItemList
                })
            }
            localStorage.setItem('cartData', JSON.stringify(cartData))
        }
    })
}

export default new Vuex.Store({

    strict: true,
    modules: {
        user,
        cart
    },
    plugins: [LoginPlugin, CartPlugin]
})
